package com.ruoyi.hiscomm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.hiscomm.domain.DeptDictDo;
import com.ruoyi.hiscomm.request.DeptParm;
import com.ruoyi.hiscomm.service.IDeptDictService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.ruoyi.common.core.utils.ListPaginator.getTotalPages;
import static com.ruoyi.common.core.utils.ListPaginator.paginate;

/**
 * @ClassName DeptDictController
 * @Author samula
 * @Descripe product by com.doctcloud
 * @Data 2025-09-28 11:52
 **/
@RestController
@RequestMapping("/deptDictCtl")
public class DeptDictController extends BaseController {
    @Resource
    private IDeptDictService deptDictService;

    @PostMapping("add")
    public AjaxResult add(@RequestBody DeptDictDo dept) throws IOException {
        String error = checkObjectValid(dept);
        if (error.length() > 0){
            return error(error);
        }
        if (deptDictService.checkDeptNameUnique(dept))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        int rows = deptDictService.addDeptDict(dept);
        return toAjax(rows);
    }
    @PutMapping("update")
    public AjaxResult update(@RequestBody DeptDictDo dept) throws IOException {
        String error = checkObjectValid(dept);
        if (error.length() > 0){
            return AjaxResult.error(error);
        }
        return toAjax(deptDictService.updateDeptDict(dept));
    }
    @DeleteMapping("delete")
    public AjaxResult delete(@RequestBody DeptDictDo dept) throws IOException {
        String error = checkObjectValid(dept);
        if (error.length() > 0){
            return AjaxResult.error(error);
        }
        dept.generateId();

        return toAjax(deptDictService.deleteDeptDict(dept.getId()));
    }
    @GetMapping("list")
    @ResponseBody
    public TableDataInfo list(){
        List<DeptDictDo> list = deptDictService.listDepts();
        return getDataTable(list);
    }

    @GetMapping("RpageList")
    public AjaxResult rlistPage(@RequestBody DeptParm parm){
        IPage<DeptDictDo> resultPage = deptDictService.pageRedisDeptList(parm);
        return AjaxResult.success(resultPage);
    }
    @GetMapping("pageList")
    public AjaxResult listPage(@RequestBody DeptParm parm) {
        // 防御性校验：确保parm不为null
        if (parm == null) {
            parm = new DeptParm();
        }
        // 处理分页参数默认值（已确保非null）
        int currentPage = parm.getCurrentPage() == null || parm.getCurrentPage() < 1
                ? 1
                : parm.getCurrentPage();
        int pageSize = parm.getPageSize() == null || parm.getPageSize() < 1
                ? 10
                : parm.getPageSize();
        // 限制最大页大小，避免一次性查询过多数据
        pageSize = Math.min(pageSize, 100);
        IPage<DeptDictDo> resultPage = new Page<>(currentPage, pageSize);
        // 无搜索词时，从缓存/数据库查询
        if (StringUtils.isEmpty(parm.getDeptName())) {
            List<DeptDictDo> allDepts = deptDictService.listDepts();
            allDepts = allDepts == null ? new ArrayList<>() : allDepts; // 防止null
            int total = allDepts.size();
            resultPage.setTotal(total);
            resultPage.setPages(getTotalPages(allDepts, pageSize)); // 使用处理后的pageSize
            resultPage.setRecords(paginate(allDepts, currentPage, pageSize)); // 使用处理后的参数
        } else {
            // 有搜索词时，调用ES分页查询
            IPage<DeptDictDo> esPage = deptDictService.pageESDeptList(parm);
            resultPage = esPage != null ? esPage : resultPage; // 防御性处理
        }
        return AjaxResult.success(resultPage);
    }

    private String checkObjectValid(DeptDictDo dept){
        String errorInfo = "";
        if (ObjectUtils.isEmpty(dept)){
            return "空数据无法处理";
        }
        if (StringUtils.isEmpty(dept.getDeptName()) || StringUtils.isEmpty(dept.getDeptCode()) || StringUtils.isEmpty(dept.getHospitalId())){
            return "无效传值,[科室名称、科室代码、医院标识]不得为空";
        }
        return errorInfo;
    }
}
